package cn.xx.controller;

import cn.xx.controller.viewobject.ItemVO;
import cn.xx.error.BusinessException;
import cn.xx.response.CommonReturnType;
import cn.xx.service.CacheService;
import cn.xx.service.ItemService;
import cn.xx.service.PromoService;
import cn.xx.service.model.ItemModel;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author xiexu
 * @create 2022-04-21 11:37
 */
@Controller("item")
@RequestMapping("/item")
//跨域请求中，不能做到session共享
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
public class ItemController extends BaseController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PromoService promoService;

    //创建商品的controller
    @RequestMapping(value = "/create", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType createItem(@RequestParam(name = "title") String title, @RequestParam(name = "description") String description, @RequestParam(name = "price") BigDecimal price, @RequestParam(name = "stock") Integer stock, @RequestParam(name = "imgUrl") String imgUrl) throws BusinessException {
        //封装service请求用来创建商品
        ItemModel itemModel = new ItemModel();
        itemModel.setTitle(title);
        itemModel.setDescription(description);
        itemModel.setPrice(price);
        itemModel.setStock(stock);
        itemModel.setImgUrl(imgUrl);

        ItemModel itemModelForReturn = itemService.createItem(itemModel);
        ItemVO itemVO = convertVOFromModel(itemModelForReturn);
        return CommonReturnType.create(itemVO);
    }

    private ItemVO convertVOFromModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemVO itemVO = new ItemVO();
        //将itemModel拷贝到itemVO
        BeanUtils.copyProperties(itemModel, itemVO);
        //如果这个itemModel的PromoModel属性不为空，说明有正在进行的秒杀活动
        if (itemModel.getPromoModel() != null) {
            //有正在进行或即将开始的秒杀活动
            //则需要将秒杀活动的相关信息也一起设置到itemVO里面
            itemVO.setPromoStatus(itemModel.getPromoModel().getStatus()); //活动状态
            itemVO.setPromoId(itemModel.getPromoModel().getId()); //活动id
            itemVO.setStartDate(itemModel.getPromoModel().getStartDate().toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))); //活动开始时间
            itemVO.setPromoPrice(itemModel.getPromoModel().getPromoItemPrice()); //活动价格
        } else {
            //没有秒杀活动就将status设置为0
            itemVO.setPromoStatus(0);
        }
        return itemVO;
    }

    //商品详情页浏览
    @RequestMapping(value = "/get", method = {RequestMethod.GET})
    @ResponseBody
    // 这个@RequestParam表示这个参数是必传的，如果没传则会报ServletRequestBindingException错误，然后被GlobalExceptionHandler类所捕获
    public CommonReturnType getItem(@RequestParam(name = "id") Integer id) {

        ItemModel itemModel = null;

        // 1.先取本地缓存
        itemModel = (ItemModel) cacheService.getFromCommonCache("item_" + id);

        // 2.若本地缓存不存在，则取redis缓存
        if (itemModel == null) {
            // 根据商品id到redis里面获取itemModel
            itemModel = (ItemModel) redisTemplate.opsForValue().get("item_" + id);

            // 3.若redis里面不存在对应的itemModel，则到数据库里面获取数据
            if (itemModel == null) {
                itemModel = itemService.getItemById(id);
                // 并且把获取到的itemModel设置到redis里面
                redisTemplate.opsForValue().set("item_" + id, itemModel);
                // 设置redis缓存过期时间为10分钟
                redisTemplate.expire("item_" + id, 10, TimeUnit.MINUTES);
            }

            // 填充本地缓存
            cacheService.setCommonCache("item_" + id, itemModel);
        }

        //将itemModel转为itemVO
        ItemVO itemVO = convertVOFromModel(itemModel);
        return CommonReturnType.create(itemVO);
    }

    //商品列表页面浏览
    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listItem() {
        // 获取所有商品信息
        List<ItemModel> itemModelList = itemService.listItem();

        // 使用 stream.api 将itemModel集合 转化为 ItemVO集合
        List<ItemVO> itemVOList = itemModelList.stream().map(itemModel -> {
            ItemVO itemVO = this.convertVOFromModel(itemModel);
            return itemVO;
        }).collect(Collectors.toList());

        return CommonReturnType.create(itemVOList);
    }

    /**
     * 发布活动信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/publishpromo", method = {RequestMethod.GET})
    @ResponseBody
    // 这个@RequestParam表示这个参数是必传的，如果没传则会报ServletRequestBindingException错误，然后被GlobalExceptionHandler类所捕获
    public CommonReturnType publishpromo(@RequestParam(name = "id") Integer id) {
        promoService.publishPromo(id);
        return CommonReturnType.create(null);
    }

}
